<template>
  <div>
    <el-upload
      v-show="!isShowProgress"
      :class="['avatar-uploader','fileList.length !==0 && limit !==0&& fileList >= limit ?disabled']"
      action="#"
      accept="image/gif,image/jpeg,image/png"
      list-type="picture-card"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onchange"
      :http-request="onRequest"
      :limit="limit"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :on-exceed="onExceed"
    >
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
      <i class="el-icon-plus avatar-uploader-icon" />
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// const COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
  SecretId: 'AKID4xbzqWw85mDRSEl36tQilY5NQDjz2rQj',
  SecretKey: 'ECuMZYHkyxg9ML5ZoumPm49yXv61g5HF'
})
console.log(cos)
export default {
  props: {
    limit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      imageUrl: '',
      fileList: [
        // {
        //   name: 'food.jpeg',
        //   uid: '10',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // }
      ],
      dialogVisible: false,
      percentage: 0,
      isShowProgress: false
    }
  },

  created() {},

  methods: {
    // 发送请求
    onRequest(data) {
      this.isShowProgress = true
      this.id = setInterval(() => {
        if (this.percentage < 97) {
          this.percentage++
        } else {
          clearInterval(this.id)
          this.percentage = 99
        }
      }, 50)
      cos.putObject(
        {
          Bucket: 'hr-sass-24-1305132301' /* 必须 */,
          Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
          Key: data.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: progressData => {
            console.log(JSON.stringify(progressData))
            if (progressData.percent === 1) {
              clearInterval(this.id)
              this.percentage = 100
              setTimeout(() => {
                this.isShowProgress = false
              }, 500)
            }
          }
        },
        (err, data) => {
          if (err) {
            this.isShowProgress = false
            this.$message.error('网络错误,上传失败')
            this.fileList.splice(this.fileList.length - 1, 1)
          }
          if (!err && data.statusCode === 200) {
            console.log('图片上传成功')
            console.log(data.Location)
            const urlIndex = this.fileList.length - 1
            this.fileList[urlIndex].url = 'https://' + data.Location
            console.log(this.fileList[0].url)
            this.$emit('on-success', this.fileList)
          }
          console.log(err || data)
        }
      )
    },
    // 点击预览
    onPreview(file) {
      this.imageUrl = file.url
      this.dialogVisible = true
    },
    // 点击 删除
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 上传之前
    beforeUpload(file) {
      const imageType = ['image/gif', 'image/jpeg', 'image/png']
      if (!imageType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      const maxSize = 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('亲，请上传1MB以内的图片')
        return false
      }
    },
    // 图片改变
    onchange(file, fileList) {
      this.fileList = fileList
    },
    onExceed() {
      this.$message.error('最多只能上传' + this.limit + '张图片')
    }
  }
}
</script>

<style lang='scss'>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
